import {
  ExceptionFilter,
  Catch,
  ArgumentsHost,
  BadRequestException,
  UnauthorizedException,
  HttpStatus,
} from '@nestjs/common';
import { HttpAdapterHost } from '@nestjs/core';
import { ResponseDto } from '@src/common/dto/response.dto';

@Catch()
export class AllExceptionsFilter implements ExceptionFilter {
  constructor(private readonly httpAdapterHost: HttpAdapterHost) {}

  catch(exception: unknown, host: ArgumentsHost): void {
    const { httpAdapter } = this.httpAdapterHost;

    const ctx = host.switchToHttp();

    if (exception instanceof BadRequestException) {
      const exceptionResponse = exception.getResponse() as any;
      if (Array.isArray(exceptionResponse.message)) {
        const errors = exceptionResponse.message.map((m) => {
          const [field, ...message] = m.split(' ');
          return {
            field,
            message: message.join(' '),
          };
        });

        return httpAdapter.reply(
          ctx.getResponse(),
          ResponseDto.fail(errors),
          exception.getStatus(),
        );
      }
    }

    if (exception instanceof UnauthorizedException) {
      const exceptionResponse = exception.getResponse() as any;
      return httpAdapter.reply(
        ctx.getResponse(),
        ResponseDto.fail(exceptionResponse.message, exception.getStatus()),
        exception.getStatus(),
      );
    }

    return httpAdapter.reply(
      ctx.getResponse(),
      ResponseDto.fail('服务器内部错误', HttpStatus.INTERNAL_SERVER_ERROR),
      HttpStatus.INTERNAL_SERVER_ERROR,
    );
  }
}
